<template>
  <ul class="todo-list">
    <li v-for="task in sortedTasks" :key="task.id" :class="{ done: task.completed }">
      <input
        type="checkbox"
        :checked="task.completed"
        @change="toggle(task.id)"
      />

      <span v-if="!task.editing" @dblclick="edit(task)">
        {{ task.title }}
      </span>
      <input
        v-else
        v-model="task.title"
        @blur="save(task)"
        @keyup.enter="save(task)"
      />

      <button class="del" @click="remove(task.id)">删除</button>
    </li>
  </ul>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  tasks: { type: Array, required: true }
})
const emit = defineEmits(['toggle', 'remove', 'update'])

const sortedTasks = computed(() => {
  return [...props.tasks].sort((a, b) => a.completed - b.completed)
})

const toggle = id => emit('toggle', id)
const remove = id => emit('remove', id)
const edit = task => (task.editing = true)
const save = task => {
  task.editing = false
  emit('update', task)
}
</script>

<style scoped src="@/assets/TodoList.css"></style>
